import type { ActionType, ParamsType, ProColumns, RequestData } from '@ant-design/pro-components';
import { FooterToolbar, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, message } from 'antd';
import React, { useCallback, useRef, useState } from 'react';

interface BasicTableProps<T, U> {
  removeRule?: (keys: T[]) => Promise<void>;
  columns: ProColumns<T>[];
  renderToolBar?: () => React.ReactNode[];
  request: (params: U, sorter: any, filter: any) => Promise<RequestData<T>>;
}

const BasicTable = <T extends Record<string, any>, U extends ParamsType>({
  removeRule,
  columns,
  renderToolBar,
  request,
}: BasicTableProps<T, U>) => {
  const actionRef = useRef<ActionType>(); // 用于刷新和重置 ProTable
  const [selectedRowsState, setSelectedRows] = useState<T[]>([]); // 选中行的状态
  const intl = useIntl(); // 用于国际化
  const [messageApi, contextHolder] = message.useMessage(); // 用于显示消息

  // 处理删除操作
  const handleRemove = useCallback(async () => {
    if (!selectedRowsState?.length) {
      messageApi.warning('请选择删除项');
      return;
    }
    await removeRule?.(selectedRowsState);

    setSelectedRows([]);
    actionRef.current?.reloadAndRest?.();
    messageApi.success('删除成功，即将刷新！');
  }, [removeRule, selectedRowsState]);

  return (
    <>
      {contextHolder}
      <ProTable<T, U>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        cardBordered={true}
        rowKey="code"
        search={{ labelWidth: 120 }}
        toolBarRender={renderToolBar}
        request={request}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            console.log(selectedRows);
            setSelectedRows(selectedRows);
          },
        }}
        actionRef={actionRef}
        scroll={columns.length > 6 ? { x: 'max-content' } : { x: 0 }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button loading={false} onClick={handleRemove}>
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
        </FooterToolbar>
      )}
    </>
  );
};

export default BasicTable;
